<template>
  <div>
    <Row :gutter="10">
      <i-col span="24">
        <div>
          <vxe-toolbar :refresh="{query: reload}" custom>
            <template v-slot:buttons>
              <vxe-button v-if="hasAccessByKey('system_ad_save')" size="mini" icon="vxe-icon--plus" content="新增" @click="AddEnable = true"></vxe-button>
<!--              <vxe-button v-if="hasAccessByKey('system_ad_del')" size="mini" status="danger" icon="iconfont icon-delete-fill" style="margin-left: 10px;"-->
<!--                          content="批量删除" @click="positionDel"></vxe-button>-->
            </template>
          </vxe-toolbar>
          <vxe-table
            style="margin-top: 10px;"
            id="toolbar_demo3"
            round
            :loading="loading"
            :custom-config="{storage: true}"
            :edit-config="{trigger: 'click', mode: 'row'}"
            highlight-current-row
            highlight-current-column
            @edit-closed="updateData"
            @checkbox-change="checkboxChange"
            @checkbox-all="checkboxChange"
            :data="tableData.result">
            <vxe-table-column type="checkbox" width="60"></vxe-table-column>
            <vxe-table-column field="id" title="ID" width="60"></vxe-table-column>

            <vxe-table-column v-if="hasAccessByKey('system_ad_edit')" field="name" title="广告名称" width="200" :edit-render="{name: 'input'}"></vxe-table-column>
            <vxe-table-column v-else field="name" title="广告名称" width="200"></vxe-table-column>

            <vxe-table-column v-if="hasAccessByKey('system_ad_edit')" field="title" title="广告标题" :edit-render="{name: 'input'}"></vxe-table-column>
            <vxe-table-column v-else field="title" title="广告标题" ></vxe-table-column>

            <vxe-table-column title="广告图片" >
              <template v-slot:default="{row}">
                <img class="icon_class" :src="row.pic">
              </template>
            </vxe-table-column>

            <vxe-table-column v-if="hasAccessByKey('system_ad_edit')" field="link" title="链接地址" :edit-render="{name: 'input'}"></vxe-table-column>
            <vxe-table-column v-else field="link" title="链接地址" width="200"></vxe-table-column>

            <vxe-table-column title="开始/结束时间">
              <template v-slot:default="{row}">
                <span style="display: block;">{{row.start_time}} --</span>
                <span>{{row.end_time}}</span>
              </template>
            </vxe-table-column>

            <vxe-table-column field="status" title="是否显示" width="100" show-overflow>
              <template v-slot:default="{row}">
                <vxe-switch  v-model="row.status" on-label="启用" off-label="禁用"
                             @change="(value)=>{statusChange(row,value)}" :disabled="!hasAccessByKey('system_ad_edit')"></vxe-switch>
              </template>
            </vxe-table-column>

            <vxe-table-column field="address" title="操作" width="250">
              <template v-slot:default="{row}">
                <vxe-button v-if="hasAccessByKey('system_ad_list')" content="编辑" @click="editAd(row)"></vxe-button>
                <vxe-button v-if="hasAccessByKey('system_ad_del')" icon="iconfont icon-delete-fill" status="danger"
                            content="删除" @click="delAd(row)"></vxe-button>
              </template>
            </vxe-table-column>
          </vxe-table>
        </div>
        <Spin size="large" fix v-if="spinShow"></Spin>
      </i-col>
    </Row>
    <Page :current="tableData.current"
          :total="tableData.total"
          :page-size="tableData.size"
          @on-change="pagerChange" @on-page-size-change="pageSizeChange" show-elevator show-sizer/>
    <template>
      <vxe-modal title="新增广告" v-model="AddEnable" resize remember transfer width="60%" height="600">
        <template v-slot>
          <new-ad @adPositionSave="reload" :position="position"></new-ad>
        </template>
      </vxe-modal>
    </template>
    <template>
      <vxe-modal title="编辑广告" v-model="editDrawer" resize remember transfer width="60%" height="600">
        <template v-slot>
          <ad-edit @adPositionSave="reload" v-if="editDrawer" :position="position" :drawer-data="drawerData"></ad-edit>
        </template>
      </vxe-modal>
    </template>
    <template>
      <verify v-if="verifyInput" @confirm="confirmDelete"></verify>
    </template>
  </div>
</template>

<script>
import PasteEditor from '_c/paste-editor'
import { adDel, adList, adEdit, adSetVal, adSave } from '@/api/ad'
import NewAd from './new-ad'
import verify from '@/components/verify'
import AdEdit from './ad-edit'

export default {
  name: 'setting_ad_list',
  components: {
    AdEdit,
    PasteEditor,
    NewAd,
    verify
  },
  data () {
    return {
      verifyInput: false,
      loading: false,
      AddEnable: false,
      search: '',
      spinShow: false,
      tableData: [],
      selection: [],
      opRole: {},
      editDrawer: false,
      drawerData: {},
      position: null
    }
  },
  mounted () {
    this.position = this.$route.params.position
    this.reload()
  },
  methods: {
    checkboxChange (event) {
      this.selection = event.selection
    },
    reload () {
      this.loading = true
      this.AddEnable = false
      this.editDrawer = false
      adList({
        position_id: this.$route.params.position
      }).then(({ data, status }) => {
        this.tableData = data.data.ad_data
        this.loading = false
      })
    },
    pagerChange (pager) {
      adList({
        page: pager
      }).then(({ data, status }) => {
        this.tableData = data.data.ad_data
        this.loading = false
      })
    },
    pageSizeChange (pageSize) {
      adList({
        page_size: pageSize
      }).then(({ data, status }) => {
        this.tableData = data.data.ad_data
        this.loading = false
      })
    },
    editAd (data) {
      this.drawerData = data
      this.editDrawer = true
    },
    updateData (data) {
      adSave(data.row).then(({ data, status }) => {
        this.$XModal.message({
          message: data.message,
          status: 'success',
          duration: 1000
        })
      }).catch((error) => {
        this.$XModal.alert({
          message: error.response.data.message,
          status: 'error'
        })
      })
    },
    statusChange (row, value) {
      adSetVal({
        id: row.id,
        field: 'status',
        value: value.value ? 1 : 0
      }).catch((error) => {
        this.$XModal.alert({
          message: error.response.data.message,
          status: 'error'
        })
      })
    },
    delAd (row) {
      if (!row.id) {
        let ids = []
        for (let key in this.selection) {
          ids.push(this.selection[key]['id'])
        }
        row.id = ids.join(',')
        if (!row.id) {
          this.$XModal.alert({
            message: '请选择要删除广告.',
            status: 'warning'
          })
          return
        }
      }
      this.$XModal.confirm('该操作将删除该广告，确认删除？', '删除').then(type => {
        if (type === 'cancel') {
          return
        }
        this.opRole = row
        this.verifyInput = false
        this.$nextTick(() => {
          this.verifyInput = true
        })
      })
    },
    confirmDelete (password) {
      adDel({
        id: this.opRole.id,
        verifyPassword: password
      }).then(({ data, status }) => {
        this.$XModal.message({
          message: data.message,
          status: 'success',
          duration: 1000
        })
        this.reload()
      }).catch(({ response }) => {
        this.$XModal.alert({
          message: response.data.message,
          status: 'error'
        })
      })
    },
    adEdit (ad) {
      const route = {
        name: 'ad-edit',
        params: {
          ad_id: ad.id
        },
        query: {
          name: ad.name
        },
        meta: {
          title: `动态路由-${ad.name}`
        }
      }
      this.$router.push(route)
    }
  }
}
</script>

<style scoped>
.icon_class {
  width: 100px;
  height: 100%;
}
</style>
